const categorys = {
    1:{text:'国内新闻', status:'1'},
    2:{text:'国际新闻', status:'2'},
    3:{text:'财经新闻', status:'3'},
    4:{text:'科技新闻', status:'4'},
};

const articles = [
    {
        id:'1',
        category: "2",
        title: "国家重要会议召开，讨论未来发展规划",
        content: "近日，国家在首都举行了重要会议，众多领导出席，共同商讨国家未来的发展方向和重点规划。"
    },
    {
        id:'2',
        category: "1",
        title: "知名演员新剧开机，粉丝期待值拉满",
        content: "备受瞩目的知名演员[演员名字]新剧今日正式开机，该剧题材新颖，从筹备起就吸引了大量粉丝关注。"
    },
];

const cateList = (req: any, res: any) =>{
    res.json({
        success: true,
        data: { list: categorys },
        errorCode: 0,
    });
}

const articleList = (req: any, res: any) =>{
    const { title='', category='' } = req.query;
    let filteredArticles = articles;
    if (title) {
        filteredArticles = filteredArticles.filter(article => article.title.includes(title));
    }
    if (category) {
        filteredArticles = filteredArticles.filter(article => article.category === category);
    }
    res.json({
        success: true,
        params:{title,category},
        data: { list: filteredArticles },
        errorCode: 0,
    });
}

const addArticle = (req: any, res: any) =>{
    const newArticle = req.body;
    articles.push(newArticle);
    res.json({
        success: true,
        data: { article: newArticle },
        errorCode: 0,
    });
}

const editArticle = (req: any, res: any) =>{
    const { id } = req.params;
    const index = articles.findIndex(article => article.id === id);
    if (index!== -1) {
        const updatedArticle = req.body;
        articles[index] = {
           ...articles[index],
           ...updatedArticle
        };
        res.json({
            success: true,
            data: { article: articles[index] },
            errorCode: 0,
        });
    } else {
        res.json({
            success: false,
            errorCode: 1,
            message: "Article not found"
        });
    }
}

const delArticle = (req: any, res: any) =>{
    const { id } = req.params;
    const index = articles.findIndex(article => article.id === id);
    if (index!== -1) {
        articles.splice(index, 1);
        res.json({
            success: true,
            errorCode: 0,
        });
    } else {
        res.json({
            success: false,
            errorCode: 1,
            message: "Article not found"
        });
    }
}

export default {
    'GET /api/v1/queryCategoryList': cateList,
    'GET /api/v1/queryArticleList': articleList,
    'POST /api/v1/article': addArticle,
    'PUT /api/v1/article/:id': editArticle,
    'DELETE /api/v1/article/:id': delArticle
};